package com.qf.bbapi.controller;

import com.qf.bbapi.config.RedisKeyConfig;
import com.qf.bbapi.dto.NearDto;
import com.qf.bbapi.dto.NearSearchDto;
import com.qf.bbapi.util.JedisUtil;
import com.qf.bbapi.vo.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.GeoCoordinate;
import redis.clients.jedis.GeoRadiusResponse;

import java.util.ArrayList;
import java.util.List;

@RestController
@Api(tags = "附近的门店")
@RequestMapping("/api/near/")
@CrossOrigin
public class NearByController {

    @ApiOperation(value = "添加门店")
    @PostMapping("add.do")
    public R add(@RequestBody NearDto dto){
        JedisUtil.addGeo(RedisKeyConfig.USER_LOCATIONS,dto.getName(),dto.getLat(),dto.getLng());
        return R.ok();
    }
    //搜索
    @ApiOperation(value = "搜索附近的门店")
    @PostMapping("search.do")
    public R search(@RequestBody NearSearchDto dto){
        List<GeoRadiusResponse> list= JedisUtil.getGeoRadius(RedisKeyConfig.USER_LOCATIONS,dto.getLat(),dto.getLng(),dto.getRadius());
        List<NearDto> result=new ArrayList<>();
        list.forEach(g ->{
            String a=g.getMemberByString();
            List<GeoCoordinate> l=JedisUtil.getGeo(RedisKeyConfig.USER_LOCATIONS,a);
            result.add(new NearDto(l.get(0).getLatitude(),
                    l.get(0).getLongitude(),
                    JedisUtil.getDist(RedisKeyConfig.USER_LOCATIONS,dto.getName(),a),
                    a));
        });
        return R.ok(result);
    }
}